#include"worker_sql_tools.h"
#include"threadPool.h"
#include"my_header.h"
#include"sendMsg.h"

#if DEBUG_MODE
      #define DEBUG_PRINT(fmt, ...) printf("[DEBUG] %s:%d: " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
#else
      #define DEBUG_PRINT(fmt, ...) do {} while(0)
#endif

// 实际定义全局变量
MYSQL *conn = NULL;
const char *host = "localhost";
const char *user = "root";
const char *password = "203018";
const char *database = "network_disk";

int my_init_db(){
    conn=mysql_init(NULL);
    DEBUG_PRINT("mysql init success\n");
    MYSQL*ret =mysql_real_connect(conn,host,user,password,database,0,NULL,0);
    if(ret==NULL){
        DEBUG_PRINT("fail to connect database%s\n",mysql_error(conn));
        exit(-1);
    }
    return 0;
}

//随机生成盐值的函数
int generate_salt(char*salt){
    const char charset[]="abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    strcpy(salt,"$6$");//前缀
    srand(time(NULL));
    for(int i=3;i<19;++i){
        int index=rand()%(sizeof(charset)-1);
        salt[i]=charset[index];
    }
    salt[19]='$';
    salt[20]='\0';
    return 0;
}

//用户注册函数
int user_register (MYSQL *conn,char*username,char*salt,char*cryptograph,int netfd){
    char query[512];
    //检查用户是否已经注册
    DEBUG_PRINT("Registered cryptograph: %s\n", cryptograph);
    sprintf(query,"select username from user_table where username='%s'",username);
    if(mysql_query(conn,query)){
        DEBUG_PRINT("query fail：%s\n",mysql_error(conn));
        sendMsg(netfd,"server system error,try later");
        return -1;
    }
    MYSQL_RES*res=mysql_store_result(conn);
    if(res==NULL){
        DEBUG_PRINT("store result fail：%s\n",mysql_error(conn));
        sendMsg(netfd,"server system error,try later");
        return -1;
    }
    MYSQL_ROW row=mysql_fetch_row(res);
    if(row!=NULL){
        //用户已经存在
        mysql_free_result(res);
        DEBUG_PRINT("user is exist,username=%s\n",username);
        sendMsg(netfd,"user is exist\n");
        return -1;
    }else{
        //新用户，插入用户表
        mysql_free_result(res);
        sprintf(query,"insert into user_table"
                    "(username,salt,cryptograph)"
                    "VALUES ('%s','%s','%s')",
                    username,salt,cryptograph);

    }
    if(mysql_query(conn,query)){
        DEBUG_PRINT("query fail：%s\n",mysql_error(conn));
        sendMsg(netfd,"register fail,try later\n");
        return -1;
    }else{
        DEBUG_PRINT("login success：username=%s",username);
        sendMsg(netfd,"register success");
    }
    return 0;
}


//用户登入函数
int user_login(MYSQL *conn,char*username,char*cryptograph,int netfd){
    char query[256];
    char stored_salt[21]={0};//用来存储用户表中的盐值
    char stored_cryptograph[107]={0};//用来存储用户表中的盐值
    //检查用户是否存在
    sprintf(query,"select salt,cryptograph from user_table where username='%s' AND is_deleted=0",username);
    if(mysql_query(conn,query)){
        DEBUG_PRINT("query fail：%s\n",mysql_error(conn));
        sendMsg(netfd,"server system error,try later");
        return -1;
    }
    MYSQL_RES*res=mysql_store_result(conn);
    if(res==NULL){
        DEBUG_PRINT("store result fail：%s\n",mysql_error(conn));
        sendMsg(netfd,"server system error,try later");
        return -1;
    }
    MYSQL_ROW row=mysql_fetch_row(res);
    if(row==NULL){
        DEBUG_PRINT("user is no exist,username=%s\n",username);
        sendMsg(netfd,"user is no exist\n");
        mysql_free_result(res);
        return -1;
    }
    mysql_free_result(res);
    DEBUG_PRINT("user is exist,username=%s\n",username);
    //用户名存在，找出其中的的盐值和密文
    strncpy(stored_salt,row[0],20);
    strncpy(stored_cryptograph,row[1],106);
    DEBUG_PRINT("Stored cryptograph: %s\n", stored_cryptograph);
    DEBUG_PRINT("Input cryptograph: %s\n", cryptograph);
    //进行密文匹配
    if(strcmp(stored_cryptograph,cryptograph)==0){
        //密码验证成功
        DEBUG_PRINT("user login succeed\n");
        sendMsg(netfd,"Password is CORRECT");
    }else{
        DEBUG_PRINT("user password fail\n");
        sendMsg(netfd,"Password is NO CORRECT");
        return -1;
    }
    return 0;
}

//用户注销函数
int user_logout (MYSQL *conn,char*username,int netfd){
    char query[512];
    sprintf(query,"update user_table set is_deleted =1 where username='%s'",username);
    if(mysql_query(conn,query)){
        DEBUG_PRINT("query fail：%s\n",mysql_error(conn));
        sendMsg(netfd,"server system error,try later");
        return -1;
    }
    DEBUG_PRINT("logout succeed");
    sendMsg(netfd,"logout succeed");
    return 0;
}


//int main(int argc, char* argv[]) {
//    init_database();
//
//     模拟网络套接字（实际测试时可替换为真实socket）
//    int test_fd = 1;
//
//    printf("\n=========== 开始单元测试 ===========\n");
//
//     测试1: 用户注册
//    printf("\n[测试1] 注册新用户\n");
//    char test_username[32] = "test_user";
//    char test_salt[32];
//    char test_cryptograph[128] = "hashed_password_123";  模拟加密后的密码
//    for(int i=0;i<10;++i){
//        generate_salt(test_salt);
//        printf("%s\n",test_salt);
//        int reg_result = user_register(test_username, test_salt, test_cryptograph, test_fd);
//        if(reg_result == 0) {
//            printf(" 注册测试成功\n");
//        } else {
//            printf(" 注册测试失败\n");
//        }
//        sleep(1);
//    }
//
//     测试2: 重复注册
//    printf("[测试2] 重复注册测试\n");
//    printf("%s\n",test_salt);
//    int reg_result = user_register(test_username, test_salt, test_cryptograph, test_fd);
//    if(reg_result == -1) {
//        printf(" 重复注册测试成功\n");
//    } else {
//        printf(" 重复注册测试失败\n");
//    }
//
//     测试3: 用户登录
//    printf("[测试3] 正确密码登录测试\n");
//    int login_result = user_login(test_username, test_cryptograph, test_fd);
//    if(login_result == 0) {
//        printf(" 登录测试成功\n");
//    } else {
//        printf(" 登录测试失败\n");
//    }
//
//     测试4: 错误密码登录
//    printf("[测试4] 错误密码登录测试\n");
//    login_result = user_login(test_username, "wrong_password", test_fd);
//    if(login_result == -1) {
//        printf(" 错误密码测试成功\n");
//    } else {
//        printf(" 错误密码测试失败\n");
//    }
//
//     测试5: 用户注销
//    printf("\n[测试5] 用户注销测试\n");
//    int logout_result = user_logout(test_username, test_fd);
//    if(logout_result == 0) {
//        printf(" 注销测试成功\n");
//    } else {
//        printf(" 注销测试失败\n");
//    }
//
//     测试6: 已注销用户登录
//    printf("\n[测试6] 已注销用户登录测试\n");
//    login_result = user_login(test_username, test_cryptograph, test_fd);
//    if(login_result == -1) {
//        printf(" 已注销用户登录测试成功（如预期拒绝）\n");
//    } else {
//        printf(" 已注销用户登录测试失败\n");
//    }
//
//    // 清理测试数据
//    char cleanup_query[256];
//    sprintf(cleanup_query, "DELETE FROM user_table WHERE username='%s'", test_username);
//    mysql_query(conn, cleanup_query);
//
//    printf("\n=========== 测试完成 ===========\n");
//
//    mysql_close(conn);
//    return 0;
//}
//

